package es.cazadoresmadridejos.beans.dao.adviced.impl;

import java.sql.SQLException;

import org.displaytag.pagination.PaginatedList;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import es.cazadoresmadridejos.beans.dao.adviced.AdvicedDao;
import es.cazadoresmadridejos.common.bean.dao.impl.DaoImpl;
import es.cazadoresmadridejos.model.Adviced;
import es.cazadoresmadridejos.objs.web.Page;
import es.cazadoresmadridejos.objs.web.PaginatedListImpl;

@Repository("advicedDao")
public class AdvicedDaoImpl extends DaoImpl<Adviced> implements AdvicedDao{

	@Override
	public Adviced newInstance() {
		return new Adviced();
	}

	@Override
	public PaginatedList findAllPaginated(final Page page, final Long reason) {
		return (PaginatedList)getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				
				StringBuilder hql = new StringBuilder();
				StringBuilder hqlCount = new StringBuilder();
				hql.append("select a ");
				hql.append(" from Adviced a ");
				hql.append(" where a.reason.year = :reason ");
				hql.append(getSort(page,"a"));
				
				
				hqlCount.append("select count(a) ");
				hqlCount.append(" from Adviced a ");
				hqlCount.append(" where a.reason.year = :reason ");
				
				Query query = session.createQuery(hql.toString());
				Query queryCount = session.createQuery(hqlCount.toString());
				
				query.setLong("reason", reason);
				queryCount.setLong("reason", reason);
				
				query.setMaxResults(page.getLimit());
				query.setFirstResult(page.getLimit() * (page.getPage() - 1));
				
				return new PaginatedListImpl<Object>(query.list(), 
						page, 
						((Long)queryCount.uniqueResult()).intValue());
			}
		});
	}

}
